package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private UserService userService;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    /**
     * 新建工单
     *
     * @param taskViewModel
     * @return
     */


    @Override
    @Transactional
    public boolean createTask(TaskViewModel taskViewModel) {
        // 查询本台机器的同类型未完成的工单数量.
        int undoneNumber = checkVMTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());
        if (undoneNumber >= 1) {
            // 不能创建同类型已经存在的工单
            throw new LogicException("工单已经创建,不能重复创建");
        }

        // 远程调用用户微服务,查询执行人名称
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (ObjectUtils.isEmpty(user)) {
            throw new LogicException("用户不存在");
        }
        // 远程调用售货机微服务,查询售货机信息
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (ObjectUtils.isEmpty(vm)) {

            throw new LogicException("售货机不存在");
        }
        // 投放工单,状态为运营,抛异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY // 投放工单
                && vm.getVmStatus() == VMSystem.VM_STATUS_RUNNING) { // 状态运营
            throw new LogicException("售货机状态是运营中!!不能投放");
        }
        // 补货工单,状态不是运营状态,抛异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY // 补货工单
                && vm.getVmStatus() != VMSystem.VM_STATUS_RUNNING) { // 状态非运营
            throw new LogicException("售货机状态不是运营中!!不能补货");
        }
        // 撤机工单,状态不是运营状态
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_REVOKE // 撤机工单
                && vm.getVmStatus() != VMSystem.VM_STATUS_RUNNING) { // 状态非运营
            throw new LogicException("售货机状态不是运营中!!不能撤机");
        }


        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        taskEntity.setUserName(user.getUserName()); // 执行人名称
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE); // 工单状态
        taskEntity.setRegionId(vm.getRegionId()); // 所属区域ID
        taskEntity.setAddr(vm.getNodeAddr()); // 地址
        taskEntity.setTaskCode(generateTaskCode()); // taskCode
        taskEntity.setProductTypeId(taskViewModel.getProductType()); // 工单类型ID
        if (save(taskEntity)) {
            // 判断工单是否是补货工单
            if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
                List<TaskDetailsViewModel> details = taskViewModel.getDetails();
                // 补货明细不能为空
                if (!CollectionUtils.isEmpty(details)) {
                    // 插入补货记录表
                    for (TaskDetailsViewModel detail : details) {
                        TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                        BeanUtils.copyProperties(detail, taskDetailsEntity);
                        taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                        taskDetailsService.save(taskDetailsEntity);
                    }
                }
            }
            // 创建工单,给当前的工单执行人分数+1
            updateTaskRole(taskEntity, 1);
            return true;
        }
        return false;
    }

    /**
     * 同一台设备未完成的同类型的工单数量
     *
     * @param innerCode
     * @param productType
     * @return
     */
    private int checkVMTask(String innerCode, int productType) {
        LambdaQueryWrapper<TaskEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TaskEntity::getInnerCode, innerCode);
        lqw.eq(TaskEntity::getProductTypeId, productType);
        lqw.le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        // 符合条件的个数
        int count = count(lqw);
        return count;
    }

    /**
     * 接受工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean acceptTask(Long taskId) {
        TaskEntity taskEntity = getById(taskId);
        // 工单不是待处理状态,不能领取工单
        if (taskEntity.getTaskStatus().intValue() != VMSystem.TASK_STATUS_CREATE.intValue()) {
            throw new LogicException("工单不能被领取!");
        }
        // 修改状态为进行中
        TaskEntity pojo = new TaskEntity();
        pojo.setTaskId(taskId);
        pojo.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        if (updateById(pojo)) {
            return true;
        }
        return false;
    }


    /**
     * 取消工单
     *
     * @param taskId
     * @param cancelTaskViewModel
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId, CancelTaskViewModel cancelTaskViewModel) {
        TaskEntity taskEntity = getById(taskId);
        // 不是进行中的工单不能取消
        if (taskEntity.getTaskStatus().intValue() != VMSystem.TASK_STATUS_PROGRESS.intValue()) {
            throw new LogicException("工单状态不是进行中!");
        }
        TaskEntity pojo = new TaskEntity();
        pojo.setTaskId(taskId);
        pojo.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        pojo.setDesc(cancelTaskViewModel.getDesc());
        if (updateById(pojo)) {
            // 需要更新redis的单数,单数-1
            updateTaskRole(taskEntity, -1);
            return true;
        }
        return false;
    }

    /**
     * 完成工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean completeTask(Long taskId) {
        TaskEntity taskEntity = getById(taskId);
        if (taskEntity.getTaskStatus() != VMSystem.TASK_STATUS_PROGRESS) {
            throw new LogicException("工单状态已经是完成!!");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        updateById(taskEntity);

        // 判断工单类型是运维还是运营工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY
                || taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {  // 运维工单
            // 发送消息封装
            TaskCompleteContract completeContract = new TaskCompleteContract();
            completeContract.setInnerCode(taskEntity.getInnerCode());
            completeContract.setTaskType(taskEntity.getProductTypeId());
            // 发送消息
            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, completeContract);
            } catch (JsonProcessingException e) {
                log.error("发送消息失败!");
                throw new LogicException("发送消息失败!");
            }
        }

        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) { //补货工单
            // 根据id查询补货数据
            List<TaskDetailsEntity> taskDetailsList = taskDetailsService.getByTaskId(taskId);
            // 复制参数
            List<SupplyChannel> supplyChannelList = taskDetailsList.stream().map(taskDetailsEntity -> {
                SupplyChannel supplyChannel = new SupplyChannel();
                BeanUtils.copyProperties(taskDetailsEntity, supplyChannel);
                supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
                supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
                return supplyChannel;
            }).collect(Collectors.toList());
            // 消息封装
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setInnerCode(taskEntity.getInnerCode());
            supplyContract.setSupplyData(supplyChannelList);
            // 发送消息
            try {
                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
            } catch (JsonProcessingException e) {
                log.error("发送消息失败!");
                throw new LogicException("发送消息失败!");
            }
        }
        return true;
    }


    /**
     * 获取同一天内分配的工单最少的人
     *
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002";
        if (isRepair) { //如果是运维工单
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + new SimpleDateFormat("yyyyMMdd").format(new Date())
                + "." + regionId
                + "." + roleCode;
        Set<String> set = redisTemplate.opsForZSet().range(key, 0, 0);
        if (!CollectionUtils.isEmpty(set)){
            return Integer.parseInt(new ArrayList<>(set).get(0));
        }
        return 0;
    }

    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        // 查询redis是否有 lkd.task.code + 日期时间的key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, String.valueOf(1L), Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    /**
     * 修改员工单数
     */
    private void updateTaskRole(TaskEntity taskEntity, int score) {
        String RoleCode = "1003"; // 维修员
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REPAIR) {
            // 维修工单
            RoleCode = "1002";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + new SimpleDateFormat("yyyyMMdd").format(new Date())
                + "." + taskEntity.getRegionId()
                + "." + RoleCode;
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId().toString(), score);
    }


}
